import { commonCaptchaImageGet } from '@/api'
import { TICKET_STATUS_MAP } from '@/const/order'
import type { AuthCodeProps, ColumnsFnProps } from '@/typed/components'
import { VehicleTruckProfile20Regular } from '@vicons/fluent'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import calendar from 'dayjs/plugin/calendar'
import updateLocale from 'dayjs/plugin/updateLocale'
import type { DataTableProps } from 'naive-ui'
import { NTooltip } from 'naive-ui'
import { h } from 'vue'

dayjs.extend(updateLocale)
dayjs.extend(calendar)
dayjs.updateLocale('zh-cn', {
	// A : 上午/下午/晚上 , dddd: 星期
	calendar: {
		lastDay: '[昨天] (dddd)',
		sameDay: '[今天] (dddd)',
		nextDay: '[明天] (dddd)',
		lastWeek: '[上]ddd',
		nextWeek: '[下]ddd',
		sameElse: 'YYYY-MM-DD'
	}
})
dayjs.locale('zh-cn') // 全局使用

export function clearNullData(
	params: any,
	clearList: (undefined | number | null | string)[] = ['', null, undefined]
) {
	let obj: any = {}
	if (params instanceof FormData) {
		return params
	}
	if (params && typeof params === 'object' && !Array.isArray(params)) {
		for (const i in params) {
			const val: any = params[i]
			if (!clearList.includes(val)) {
				obj[i] = val
			}
		}
	} else {
		obj = params
	}
	return obj
}

export function formatTime(
	time: number | string | null | undefined,
	format = 'YYYY-MM-DD HH:mm:ss'
) {
	return time ? dayjs(time).format(format) : ''
}


export async function getAuthCode(): Promise<AuthCodeProps> {
	const { data } = await commonCaptchaImageGet()
	let background = '#e9e4e4'
	if (data) {
		const svg: string = data.img.replace(/(width|height)="[^"]+"/gi, '')
		// .replace(/<path [^\/>]{0,120}(\/>|><\/path>)/ig,'')
		const color: string | undefined = svg.match(/<rect file="([^"]+)"/i)?.[1]
		if (color) {
			background = color
		}
		const baseImg = btoa(decodeURIComponent(svg))
		return {
			uuid: data.uuid,
			src: `data:image/svg+xml;base64,${baseImg}`,
			background
		}
	}
	return {
		src: '',
		uuid: '',
		background: ''
	}
}

export function encode(str: any) {
	try {
		return btoa(encodeURIComponent(str))
	} catch (e) {
		return ''
	}
}

export function decode(str: any) {
	if (str === undefined || str === null) {
		return ''
	}
	try {
		return decodeURIComponent(atob(str))
	} catch (e) {
		return ''
	}
}

export function getNumber(value: any, defaultValue?: any) {
	if (value === null || value === undefined) {
		return defaultValue
	}
	return /^\d+$/.test(value.toString()) ? Number(value) : defaultValue
}

export function renderMaybeNull(value: any) {
	if (value === null || value === '') {
		return '--'
	}
	return value
}

export function mapToList(map: any) {
	return Object.keys(map).map(i => {
		const v = /^\d+/.test(i) ? Number(i) : i;
		return {
			label: map[i],
			value: v,
			key: v,
		}
	})
}

export function renderTicketInfo(item: any) {
	return h('div', {
		style: {
			lineHeight: 1,
			display: 'flex',
			alignItems: 'center',
			justifyContent: 'flex-start'
		}
	}, [
		h(NTooltip, {
			width: 300,
		}, {
			trigger: () => h('div', {
				style: {
					display: 'flex',
					alignItems: 'center',
					gap: '10px',
					cursor: 'pointer'
				}
			}, [
				h(VehicleTruckProfile20Regular, {
					style: {
						height: 20,
						width: 20,
						color: 'var(--success-color-pressed)'
					}
				}),
				item.ticketInfo?.ticketInfo?.ticket || '无'
			]),
			default: () => h('div', {}, [
				h('div', {}, [
					item.ticketInfo.ticketInfo.ticket, `（${item.ticketInfo.ticketInfo.company}）`
				]),
				h('div', {}, [
					item.ticketInfo.addressInfo.addressUserName, ' ' + item.ticketInfo.addressInfo.addressUserPhone
				]),
				h('div', {}, [
					item.ticketInfo.addressInfo.addressUserArea || '--', ' ' + (item.ticketInfo.addressInfo.addressUserDetailAddress || '--')
				]),
				...item.ticketInfo.ticketList.map((i: any) => {
					return h('div', {}, [
						formatTime(i.ticket_time, 'MM-DD HH:mm'), ' ' + i.content + ' ' + TICKET_STATUS_MAP[i.status]
					])
				})
			])
		})
	])
}

export async function utilsCopy(txt: string) {
	await navigator.clipboard.writeText(txt)
	window.$message.success(`复制成功：${txt}`);
}

export function mergeColumns(column: DataTableProps['columns'] = [], columnMap: ColumnsFnProps) {
	let copyColumn: DataTableProps['columns'] = column ? [...column] : []
	for (const index in columnMap) {
		const subList = columnMap[index] || []
		if (index === 'end') {
			copyColumn = copyColumn.concat(subList)
		} else {
			subList.forEach((sub, subIndex) => {
				copyColumn?.splice(Number(index) + subIndex, 0, sub)
			})
		}
	}

	return copyColumn
}

// 获取权限子项选中结果
export function getCheckedList(subList: any[]): { checked: number[]; all: number[] } {
	let checked: number[] = [];
	let all: number[] = [];
	subList.forEach((i) => {
		all.push(i.menuId);
		if (i.checked) {
			checked.push(i.menuId);
		}
		if (i.children) {
			const result = getCheckedList(i.children);
			checked = checked.concat(result.checked);
			all = all.concat(result.all);
		}
	});
	return { checked, all };
}

export function diffArray(before: number[], after: number[]) {
	const add: number[] = [];
	const del: number[] = [];
	before.forEach((i) => {
		if (!after.includes(i)) {
			del.push(i);
		}
	});
	after.forEach((i) => {
		if (!before.includes(i)) {
			add.push(i);
		}
	});

	return { add, del };
}

export function debounce(func: Function, delay: number) {
	console.log(11)
	let timeoutId: any;
	return function (...args: any) {
		// 如果已经存在一个定时器，清除它
		if (timeoutId) {
			clearTimeout(timeoutId);
		}
		// 创建一个新的定时器，在指定的延迟后执行函数
		timeoutId = setTimeout(() => {
			func(...args);
		}, delay);
	};
}
